package net.lgpage.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

@SuppressLint("NewApi")
public class FileIntentUtil {
	public static String getPath(final Context context, final Uri uri) {  
		  
	    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;  
	    // DocumentProvider  
	    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {  
	        // ExternalStorageProvider  
	        if (isExternalStorageDocument(uri)) {  
	            final String docId = DocumentsContract.getDocumentId(uri);  
	            final String[] split = docId.split(":");  
	            final String type = split[0];  
	  
	            if ("primary".equalsIgnoreCase(type)) {  
	                return Environment.getExternalStorageDirectory() + "/" + split[1];  
	            }  
	  
	            // TODO handle non-primary volumes  
	        }  
	        // DownloadsProvider  
	        else if (isDownloadsDocument(uri)) {  
	  
	            final String id = DocumentsContract.getDocumentId(uri);  
	            final Uri contentUri = ContentUris.withAppendedId(  
	                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));  
	  
	            return getDataColumn(context, contentUri, null, null);  
	        }  
	        // MediaProvider  
	        else if (isMediaDocument(uri)) {  
	            final String docId = DocumentsContract.getDocumentId(uri);  
	            final String[] split = docId.split(":");  
	            final String type = split[0];  
	  
	            Uri contentUri = null;  
	            if ("image".equals(type)) {  
	                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;  
	            } else if ("video".equals(type)) {  
	                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;  
	            } else if ("audio".equals(type)) {  
	                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;  
	            }  
	  
	            final String selection = "_id=?";  
	            final String[] selectionArgs = new String[] {  
	                    split[1]  
	            };  
	            
	            return getDataColumn(context, contentUri, selection, selectionArgs);  
	        }  
	    }  
	    // MediaStore (and general)  
	    else if ("content".equalsIgnoreCase(uri.getScheme())) {  
	  
	        // Return the remote address  
	        if (isGooglePhotosUri(uri))  
	            return uri.getLastPathSegment();  
	  
	        return getDataColumn(context, uri, null, null);  
	    }  
	    // File  
	    else if ("file".equalsIgnoreCase(uri.getScheme())) {  
	        return uri.getPath();  
	    }  
	  
	    return null;  
	}  
	  
	/** 
	 * Get the value of the data column for this Uri. This is useful for 
	 * MediaStore Uris, and other file-based ContentProviders. 
	 * 
	 * @param context The context. 
	 * @param uri The Uri to query. 
	 * @param selection (Optional) Filter used in the query. 
	 * @param selectionArgs (Optional) Selection arguments used in the query. 
	 * @return The value of the _data column, which is typically a file path. 
	 */  
	public static String getDataColumn(Context context, Uri uri, String selection,  
	        String[] selectionArgs) {  
	    Cursor cursor = null;  
	    final String column = "_data";  
	    final String[] projection = {  
	            column  
	    };  
	  
	    try {  
	        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,  
	                null);  
	        if (cursor != null && cursor.moveToFirst()) {  
	            final int index = cursor.getColumnIndexOrThrow(column);  
	            return cursor.getString(index);  
	        }  
	    } finally {  
	        if (cursor != null)  
	            cursor.close();  
	    }  
	    return null;  
	}  
	  
	  
	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is ExternalStorageProvider. 
	 */  
	public static boolean isExternalStorageDocument(Uri uri) {  
	    return "com.android.externalstorage.documents".equals(uri.getAuthority());  
	}  
	  
	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is DownloadsProvider. 
	 */  
	public static boolean isDownloadsDocument(Uri uri) {  
	    return "com.android.providers.downloads.documents".equals(uri.getAuthority());  
	}  
	  
	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is MediaProvider. 
	 */  
	public static boolean isMediaDocument(Uri uri) {  
	    return "com.android.providers.media.documents".equals(uri.getAuthority());  
	}  
	  
	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is Google Photos. 
	 */  
	public static boolean isGooglePhotosUri(Uri uri) {  
	    return "com.google.android.apps.photos.content".equals(uri.getAuthority());  
	}  
    
    
    
    public static String sFileExtensions;  
    
    // Audio file types  
    public static final int FILE_TYPE_MP3     = 1;  
    public static final int FILE_TYPE_M4A     = 2;  
    public static final int FILE_TYPE_WAV     = 3;  
    public static final int FILE_TYPE_AMR     = 4;  
    public static final int FILE_TYPE_AWB     = 5;  
    public static final int FILE_TYPE_WMA     = 6;  
    public static final int FILE_TYPE_OGG     = 7;  
    private static final int FIRST_AUDIO_FILE_TYPE = FILE_TYPE_MP3;  
    private static final int LAST_AUDIO_FILE_TYPE = FILE_TYPE_OGG;  
  
    // MIDI file types  
    public static final int FILE_TYPE_MID     = 11;  
    public static final int FILE_TYPE_SMF     = 12;  
    public static final int FILE_TYPE_IMY     = 13;  
    private static final int FIRST_MIDI_FILE_TYPE = FILE_TYPE_MID;  
    private static final int LAST_MIDI_FILE_TYPE = FILE_TYPE_IMY;  
     
    // Video file types  
    public static final int FILE_TYPE_MP4     = 21;  
    public static final int FILE_TYPE_M4V     = 22;  
    public static final int FILE_TYPE_3GPP    = 23;  
    public static final int FILE_TYPE_3GPP2   = 24;  
    public static final int FILE_TYPE_WMV     = 25;  
    private static final int FIRST_VIDEO_FILE_TYPE = FILE_TYPE_MP4;  
    private static final int LAST_VIDEO_FILE_TYPE = FILE_TYPE_WMV;  
      
    // Image file types  
    public static final int FILE_TYPE_JPEG    = 31;  
    public static final int FILE_TYPE_GIF     = 32;  
    public static final int FILE_TYPE_PNG     = 33;  
    public static final int FILE_TYPE_BMP     = 34;  
    public static final int FILE_TYPE_WBMP    = 35;  
    private static final int FIRST_IMAGE_FILE_TYPE = FILE_TYPE_JPEG;  
    private static final int LAST_IMAGE_FILE_TYPE = FILE_TYPE_WBMP;  
     
    // Playlist file types  
    public static final int FILE_TYPE_M3U     = 41;  
    public static final int FILE_TYPE_PLS     = 42;  
    public static final int FILE_TYPE_WPL     = 43;  
    private static final int FIRST_PLAYLIST_FILE_TYPE = FILE_TYPE_M3U;  
    private static final int LAST_PLAYLIST_FILE_TYPE = FILE_TYPE_WPL;  
      
    //静态内部类  
    static class MediaFileType {  
      
        int fileType;  
        String mimeType;  
          
        MediaFileType(int fileType, String mimeType) {  
            this.fileType = fileType;  
            this.mimeType = mimeType;  
        }  
    }  
      
    private static HashMap<String, MediaFileType> sFileTypeMap   
            = new HashMap<String, MediaFileType>();  
    private static HashMap<String, Integer> sMimeTypeMap   
            = new HashMap<String, Integer>();              
    static void addFileType(String extension, int fileType, String mimeType) {  
        sFileTypeMap.put(extension, new MediaFileType(fileType, mimeType));  
        sMimeTypeMap.put(mimeType, new Integer(fileType));  
    }  
    static {  
        addFileType("MP3", FILE_TYPE_MP3, "audio/mpeg");  
        addFileType("M4A", FILE_TYPE_M4A, "audio/mp4");  
        addFileType("WAV", FILE_TYPE_WAV, "audio/x-wav");  
        addFileType("AMR", FILE_TYPE_AMR, "audio/amr");  
        addFileType("AWB", FILE_TYPE_AWB, "audio/amr-wb");  
        addFileType("WMA", FILE_TYPE_WMA, "audio/x-ms-wma");      
        addFileType("OGG", FILE_TYPE_OGG, "application/ogg");      
   
        addFileType("MID", FILE_TYPE_MID, "audio/midi");  
        addFileType("XMF", FILE_TYPE_MID, "audio/midi");  
        addFileType("RTTTL", FILE_TYPE_MID, "audio/midi");  
        addFileType("SMF", FILE_TYPE_SMF, "audio/sp-midi");  
        addFileType("IMY", FILE_TYPE_IMY, "audio/imelody");  
          
        addFileType("MP4", FILE_TYPE_MP4, "video/mp4");  
        addFileType("M4V", FILE_TYPE_M4V, "video/mp4");  
        addFileType("3GP", FILE_TYPE_3GPP, "video/3gpp");  
        addFileType("3GPP", FILE_TYPE_3GPP, "video/3gpp");  
        addFileType("3G2", FILE_TYPE_3GPP2, "video/3gpp2");  
        addFileType("3GPP2", FILE_TYPE_3GPP2, "video/3gpp2");  
        addFileType("WMV", FILE_TYPE_WMV, "video/x-ms-wmv");  
  
        addFileType("JPG", FILE_TYPE_JPEG, "image/jpeg");  
        addFileType("JPEG", FILE_TYPE_JPEG, "image/jpeg");  
        addFileType("GIF", FILE_TYPE_GIF, "image/gif");  
        addFileType("PNG", FILE_TYPE_PNG, "image/png");  
        addFileType("BMP", FILE_TYPE_BMP, "image/x-ms-bmp");  
        addFileType("WBMP", FILE_TYPE_WBMP, "image/vnd.wap.wbmp");  
   
        addFileType("M3U", FILE_TYPE_M3U, "audio/x-mpegurl");  
        addFileType("PLS", FILE_TYPE_PLS, "audio/x-scpls");  
        addFileType("WPL", FILE_TYPE_WPL, "application/vnd.ms-wpl");  
  
        // compute file extensions list for native Media Scanner  
        StringBuilder builder = new StringBuilder();  
        Iterator<String> iterator = sFileTypeMap.keySet().iterator();  
          
        while (iterator.hasNext()) {  
            if (builder.length() > 0) {  
                builder.append(',');  
            }  
            builder.append(iterator.next());  
        }   
        sFileExtensions = builder.toString();  
    }  
      
    public static final String UNKNOWN_STRING = "<unknown>";  
      
    public static boolean isAudioFileType(int fileType) {  
        return ((fileType >= FIRST_AUDIO_FILE_TYPE &&  
                fileType <= LAST_AUDIO_FILE_TYPE) ||  
                (fileType >= FIRST_MIDI_FILE_TYPE &&  
                fileType <= LAST_MIDI_FILE_TYPE));  
    }  
      
    public static boolean isVideoFileType(int fileType) {  
        return (fileType >= FIRST_VIDEO_FILE_TYPE &&  
                fileType <= LAST_VIDEO_FILE_TYPE);  
    }  
      
    public static boolean isImageFileType(int fileType) {  
        return (fileType >= FIRST_IMAGE_FILE_TYPE &&  
                fileType <= LAST_IMAGE_FILE_TYPE);  
    }  
      
    public static boolean isPlayListFileType(int fileType) {  
        return (fileType >= FIRST_PLAYLIST_FILE_TYPE &&  
                fileType <= LAST_PLAYLIST_FILE_TYPE);  
    }  
      
    public static MediaFileType getFileType(String path) {  
        int lastDot = path.lastIndexOf(".");  
        if (lastDot < 0)  
            return null;  
        return sFileTypeMap.get(path.substring(lastDot + 1).toUpperCase());  
    }  
    //根据视频文件路径判断文件类型  
    public static boolean isVideoFileType(String path) {  //自己增加  
        MediaFileType type = getFileType(path);  
        if(null != type) {  
            return isVideoFileType(type.fileType);  
        }  
        return false;  
    }  
    //根据视频文件路径判断文件类型  
    public static boolean isImageFileType(String path) {  //自己增加  
        MediaFileType type = getFileType(path);  
        if(null != type) {  
            return isImageFileType(type.fileType);  
        }  
        return false;  
    }  
    //根据音频文件路径判断文件类型  
    public static boolean isAudioFileType(String path) {  //自己增加  
        MediaFileType type = getFileType(path);  
        if(null != type) {  
            return isAudioFileType(type.fileType);  
        }  
        return false;  
    }  
    //根据mime类型查看文件类型  
    public static int getFileTypeForMimeType(String mimeType) {  
        Integer value = sMimeTypeMap.get(mimeType);  
        return (value == null ? 0 : value.intValue());  
    }  
    
    
    public static Intent openFile(String filePath){

		File file = new File(filePath);
		System.out.println(file.exists());
		if(!file.exists()) return null;
		/* 取得扩展�?*/
		String end=file.getName().substring(file.getName().lastIndexOf(".") + 1,file.getName().length()).toLowerCase(); 
		/* 依扩展名的类型决定MimeType */
		if(end.equals("m4a")||end.equals("mp3")||end.equals("mid")||
				end.equals("xmf")||end.equals("ogg")||end.equals("wav")){
			return getAudioFileIntent(filePath);
		}else if(end.equals("3gp")||end.equals("mp4")){
			return getAudioFileIntent(filePath);
		}else if(end.equals("jpg")||end.equals("gif")||end.equals("png")||
				end.equals("jpeg")||end.equals("bmp")){
			return getImageFileIntent(filePath);
		}else if(end.equals("apk")){
			return getApkFileIntent(filePath);
		}else if(end.equals("ppt")){
			return getPptFileIntent(filePath);
		}else if(end.equals("xls")){
			return getExcelFileIntent(filePath);
		}else if(end.equals("doc")){
			return getWordFileIntent(filePath);
		}else if(end.equals("pdf")){
			return getPdfFileIntent(filePath);
		}else if(end.equals("chm")){
			return getChmFileIntent(filePath);
		}else if(end.equals("txt")){
			return getTextFileIntent(filePath,false);
		}else{
			System.out.println("all");
			return getAllIntent(filePath);
		}
	}
	
	//Android获取�?��用于打开APK文件的intent
	public static Intent getAllIntent( String param ) {
		Intent intent = new Intent();  
		//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
		intent.setAction(android.content.Intent.ACTION_VIEW);  
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri,"*/*"); 
		return intent;
	}
	//Android获取�?��用于打开APK文件的intent
	public static Intent getApkFileIntent( String param ) {

		Intent intent = new Intent();  
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
		intent.setAction(android.content.Intent.ACTION_VIEW);  
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri,"application/vnd.android.package-archive"); 
		return intent;
	}

	//Android获取�?��用于打开VIDEO文件的intent
	public static Intent getVideoFileIntent( String param ) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "video/*");
		return intent;
	}

	//Android获取�?��用于打开AUDIO文件的intent
	public static Intent getAudioFileIntent( String param ){

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "audio/*");
		return intent;
	}

	//Android获取�?��用于打开Html文件的intent   
	public static Intent getHtmlFileIntent( String param ){

		Uri uri = Uri.parse(param ).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param ).build();
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.setDataAndType(uri, "text/html");
		return intent;
	}

	//Android获取�?��用于打开图片文件的intent
	public static Intent getImageFileIntent( String param ) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "image/*");
		return intent;
	}

	//Android获取�?��用于打开PPT文件的intent   
	public static Intent getPptFileIntent( String param ){  

		Intent intent = new Intent("android.intent.action.VIEW");   
		intent.addCategory("android.intent.category.DEFAULT");   
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
		Uri uri = Uri.fromFile(new File(param ));   
		intent.setDataAndType(uri, "application/vnd.ms-powerpoint");   
		return intent;   
	}   

	//Android获取�?��用于打开Excel文件的intent   
	public static Intent getExcelFileIntent( String param ){  

		Intent intent = new Intent("android.intent.action.VIEW");   
		intent.addCategory("android.intent.category.DEFAULT");   
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
		Uri uri = Uri.fromFile(new File(param ));   
		intent.setDataAndType(uri, "application/vnd.ms-excel");   
		return intent;   
	}   

	//Android获取�?��用于打开Word文件的intent   
	public static Intent getWordFileIntent( String param ){  

		Intent intent = new Intent("android.intent.action.VIEW");   
		intent.addCategory("android.intent.category.DEFAULT");   
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
		Uri uri = Uri.fromFile(new File(param ));   
		intent.setDataAndType(uri, "application/msword");   
		return intent;   
	}   

	//Android获取�?��用于打开CHM文件的intent   
	public static Intent getChmFileIntent( String param ){   

		Intent intent = new Intent("android.intent.action.VIEW");   
		intent.addCategory("android.intent.category.DEFAULT");   
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
		Uri uri = Uri.fromFile(new File(param ));   
		intent.setDataAndType(uri, "application/x-chm");   
		return intent;   
	}   

	//Android获取�?��用于打开文本文件的intent   
	public static Intent getTextFileIntent( String param, boolean paramBoolean){   

		Intent intent = new Intent("android.intent.action.VIEW");   
		intent.addCategory("android.intent.category.DEFAULT");   
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
		if (paramBoolean){   
			Uri uri1 = Uri.parse(param );   
			intent.setDataAndType(uri1, "text/plain");   
		}else{   
			Uri uri2 = Uri.fromFile(new File(param ));   
			intent.setDataAndType(uri2, "text/plain");   
		}   
		return intent;   
	}  
	//Android获取�?��用于打开PDF文件的intent   
	public static Intent getPdfFileIntent( String param ){   

		Intent intent = new Intent("android.intent.action.VIEW");   
		intent.addCategory("android.intent.category.DEFAULT");   
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
		Uri uri = Uri.fromFile(new File(param ));   
		intent.setDataAndType(uri, "application/pdf");   
		return intent;   
	}
}